package com.credit.service;

import com.credit.dao.curri.CurriDAO;
import com.credit.dao.curri.CurriModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname CurriService
 * @Description 课程相关方法的具体实现
 */
@Service
   public class CurriService   {
   @Autowired
   CurriDAO curriDAO;



   // 获取开课信息列表，实现多条件动态查询并分页
   public Page<CurriModel> getCurriList(Integer kechengteacher, String kechengname, String kechengleibie, Pageable pageable) {
      Specification<CurriModel> specification = (Specification<CurriModel>) (root,criteriaQuery,cb) -> {
         // 存放查询条件
         List<Predicate> predicateList = new ArrayList<>();
         // like模糊查询
         if (!StringUtils.isEmpty(kechengname)) {
            Predicate namePredicate =  cb.like(root.get("kechengname"),"%" + kechengname + "%");
            predicateList.add(namePredicate);
         }
         // 精确查询String类型 课程类型 kechengleixing
         if (!StringUtils.isEmpty(kechengleibie)) {
            Predicate leibiePredicate =  cb.equal(root.get("kechengleibie"),kechengleibie);
            predicateList.add(leibiePredicate);
         }
         // 精确查询String 开课教师 kechengteacher
         if (!StringUtils.isEmpty(kechengteacher.toString())) {
            Predicate teacherIdPredicate =  cb.equal(root.get("kechengteacher"),kechengteacher);
            predicateList.add(teacherIdPredicate);
         }
         // 排序
         criteriaQuery.orderBy(cb.asc(root.get("kechengid")));
         // 最终将查询条件拼好，然后return
         Predicate[] predicates = new Predicate[predicateList.size()];
         return cb.and(predicateList.toArray(predicates));

      };
      Page<CurriModel> page = curriDAO.findAll(specification,pageable);
      return page;
   }


   }
